package com.yupi.springbootinit.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description
 * @Author minify
 * @Date 2023/12/18 21:22
 * @Project mybi-backend
 */
public class FanoutConsumer {

    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ相关信息
        factory.setHost("localhost");
        // 创建一个新的连接
        Connection connection = factory.newConnection();
        // 创建一个通道
        Channel channel = connection.createChannel();
        Channel channel1 = connection.createChannel();
        // 声明一个交换机
        String EXCHANGE_NAME = "fanout_exchange";
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        channel1.exchangeDeclare(EXCHANGE_NAME, "fanout");
        // 创建一个临时队列
        String queueName = "小王的工作队列";
        channel.queueDeclare(queueName, true, false, false, null);
        // 创建一个临时队列
        String queueName1 = "小张的工作队列";
        channel1.queueDeclare(queueName1, true, false, false, null);

        // 绑定队列和交换机
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        // 绑定队列和交换机
        channel1.queueBind(queueName1, EXCHANGE_NAME, "");


        System.out.println("Consumer Waiting Receive Message");
        DeliverCallback deliverCallback1 = (consumerTag, message) ->
                System.out.println("[小王]-Consumer Received Message -> " + new String(message.getBody()));
        DeliverCallback deliverCallback2 = (consumerTag, message) ->
                System.out.println("[小张]-Consumer Received Message -> " + new String(message.getBody()));

        // 创建消费者 监听两个工作队列
        channel.basicConsume(queueName, true, deliverCallback1, consumerTag -> {
        });
        channel1.basicConsume(queueName1, true, deliverCallback2, consumerTag -> {
        });
    }
}
